package com.zhuliwei.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.dto.AddArticleDto;
import com.zhuliwei.domain.dto.ArticleDto;
import com.zhuliwei.domain.dto.ChangeArticleStatusDto;
import com.zhuliwei.domain.entity.Article;
import com.zhuliwei.domain.entity.ArticleTag;
import com.zhuliwei.domain.entity.Notice;
import com.zhuliwei.domain.vo.ArticleDetailVo;
import com.zhuliwei.domain.vo.ArticleVo;
import com.zhuliwei.domain.vo.PageVo;
import com.zhuliwei.service.ArticleService;
import com.zhuliwei.service.ArticleTagService;
import com.zhuliwei.service.NoticeService;
import com.zhuliwei.utils.BeanCopyUtils;
import com.zhuliwei.utils.RedisCache;
import com.zhuliwei.utils.WebUtils;
import io.swagger.annotations.Api;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 后台文章管理接口控制层
 *
 * @author 朱力维
 * @time 2022/10/28 9:34
 **/
@RestController
@RequestMapping("/content/article")
@Api(tags = "文章", description = "文章管理相关接口")
public class ArticleController {
    @Resource
    private ArticleService articleService;

    @Resource
    private ArticleTagService articleTagService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private NoticeService noticeService;

    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermission('content:article:list')")
    public ResponseResult<PageVo> list(Integer pageNum, Integer pageSize, ArticleDto articleDto) {
        return articleService.pageArticleList(pageNum, pageSize, articleDto);
    }

    @GetMapping("/{id}")
    public ResponseResult articleDetail(@PathVariable String id) {
        Article article = articleService.getById(id);
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        // 获取文章标签
        LambdaQueryWrapper<ArticleTag> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ArticleTag::getArticleId,id);
        lqw.select(ArticleTag::getTagId);
        List<ArticleTag> articleTags = articleTagService.list(lqw);
        if (!CollectionUtils.isEmpty(articleTags)){
            List<String> tagIds = articleTags.stream().map(articleTag -> articleTag.getTagId()).collect(Collectors.toList());
//            articleDetailVo.setTags(tagService.getBaseMapper().selectBatchIds(tagIds).stream().map(tag -> tag.getName()).collect(Collectors.toList()));
            articleDetailVo.setTags(tagIds);
        }
        return ResponseResult.okResult(articleDetailVo);
    }

    @PutMapping
    @PreAuthorize("@ps.hasPermission('content:article:update')")
    public ResponseResult updateArticle(@RequestBody AddArticleDto article){
        return articleService.updateArticle(article);
    }

    @PostMapping
    @PreAuthorize("@ps.hasPermission('content:article:release')")
    public ResponseResult add(@RequestBody AddArticleDto article) {
        return articleService.add(article);
    }


    @DeleteMapping("/{ids}")
    @Transactional
    @PreAuthorize("@ps.hasPermission('content:article:delete')")
    public ResponseResult delArticle(@PathVariable List<String> ids) {
        // 删除文章表
        articleService.removeByIds(ids);
        // 删除文章标签关联表
        for (String id:ids
        ) {
            LambdaQueryWrapper<ArticleTag> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ArticleTag::getArticleId,id);
            articleTagService.remove(lqw);
            // 删除缓存中该文章的点赞列表
            redisCache.delCacheMapValue(SystemConstants.LIKES_MAP_PREFIX, id);
            // 删除通知表
            LambdaQueryWrapper<Notice> lqwN = new LambdaQueryWrapper<>();
            lqwN.eq(Notice::getArticleId,id);
            noticeService.remove(lqwN);
        }
        return ResponseResult.okResult();
    }

    /**
     * 将草稿文章发布
     * @param articleDto
     * @return
     */
    @PutMapping("/changeArticleStatus")
    @PreAuthorize("@ps.hasPermission('content:article:releaseDraft')")
    public ResponseResult changeArticleStatus(@RequestBody ChangeArticleStatusDto articleDto){
        Article article = articleService.getById(articleDto.getId());
        article.setStatus(articleDto.getStatus());
        articleService.updateById(article);
        return ResponseResult.okResult();
    }


    @GetMapping("/export")
    @PreAuthorize("@ps.hasPermission('content:article:export')")
    public void export(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("文章.xlsx",response);
            //获取需要导出的数据
            List<Article> articles = articleService.list();
            List<ArticleVo> articleVos = BeanCopyUtils.copyBeanList(articles, ArticleVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ArticleVo.class).autoCloseStream(Boolean.FALSE).sheet("文章导出")
                    .doWrite(articleVos);

        } catch (Exception e) {
            //如果出现异常也要响应json
//            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
//            WebUtils.renderString(response, JSON.toJSONString(result));
            e.printStackTrace();
//            throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR);
        }
    }
}
